<template>
  <div>
    <a-modal
      v-model:visible="visible"
      title="发票预览"
      width="60%"
      :bodyStyle="{ maxHeight: '80vh', overflow: 'auto' }"
    >
      <template #footer>
        <a-button key="back" @click="handleCancel">
          取消
        </a-button>
        <a-button key="submit" type="primary" v-print="printObj">
          打印
        </a-button>
      </template>
      <div id="printArea" class="invoice-print">
        <div class="invoice-content">
          <div class="invoice-header">
            <div class="company-info">
              <h1>XX有限公司</h1>
              <p>地址: 北京市海淀区XX路XX号</p>
              <p>电话: 010-12345678</p>
              <p>传真: 010-87654321</p>
            </div>
            <div class="invoice-title">
              <h2>销售发票</h2>
              <p>SALES INVOICE</p>
            </div>
          </div>

          <div class="invoice-details">
            <div class="customer-info">
              <p><strong>客户名称：</strong>{{ invoiceData.customerName }}</p>
              <p><strong>地址：</strong>{{ invoiceData.customerAddress }}</p>
            </div>
            <div class="invoice-info">
              <p><strong>发票编号：</strong>{{ invoiceData.invoiceNumber }}</p>
              <p><strong>日期：</strong>{{ invoiceData.invoiceDate }}</p>
            </div>
          </div>

          <div class="invoice-body">
            <div class="table-container">
              <table class="invoice-table">
                <thead>
                <tr>
                  <th>商品描述</th>
                  <th>数量</th>
                  <th>单价</th>
                  <th>金额</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="item in invoiceData.items" :key="item.id">
                  <td>{{ item.description }}</td>
                  <td>{{ item.quantity }}</td>
                  <td>¥ {{ item.price.toFixed(2) }}</td>
                  <td>¥ {{ (item.quantity * item.price).toFixed(2) }}</td>
                </tr>
                </tbody>
              </table>
            </div>
          </div>

          <div class="invoice-footer">
            <div class="signature-section">
              <div class="signature-item" v-for="item in signatureItems" :key="item">
                <div class="signature-line"></div>
                <p>{{ item }}</p>
              </div>
            </div>

            <div class="invoice-summary">
              <div class="summary-item">
                <span>小计：¥ {{ subtotal.toFixed(2) }} | 税额 (13%)：¥ {{ tax.toFixed(2) }} | 总计：¥ {{
                    total.toFixed(2)
                  }} | Grand Total 数量总计: {{ totalQuantity }} | 金额总计: ¥ {{ total.toFixed(2) }}</span>
              </div>
            </div>

            <div class="amount-in-words">
              <p>金额大写: {{ amountInWords }}</p>
            </div>

            <div class="print-info">
              打印人: {{ printedBy }} 打印日期: {{ printDate }}
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script>
// import {getInvoiceData} from '@/api/api'
import {Modal} from 'ant-design-vue'

export default {
  name: 'PrintInvoice',
  components: {
    AModal: Modal
  },
  props: {
    billId: String
  },
  data() {
    return {
      visible: false,
      invoiceData: {
        customerName: '',
        customerAddress: '',
        invoiceNumber: '',
        invoiceDate: '',
        items: []
      },
      printedBy: 'John Doe', // 这里应该是实际的用户名
      printDate: new Date().toLocaleDateString(),
      signatureItems: ['Prepared by', 'Checked by', 'Approved by', 'Authorised By'],
      printObj: {
        id: 'printArea',
        popTitle: '发票打印',
        extraCss: '',
        extraHead: '<meta http-equiv="Content-Language" content="zh-cn"/>'
      }
    }
  },
  computed: {
    subtotal() {
      return this.invoiceData.items.reduce((sum, item) => sum + item.quantity * item.price, 0)
    },
    tax() {
      return this.subtotal * 0.13
    },
    total() {
      return this.subtotal + this.tax
    },
    totalQuantity() {
      return this.invoiceData.items.reduce((sum, item) => sum + item.quantity, 0)
    },
    amountInWords() {
      // 这里需要一个函数来将数字转换为英文单词
      // 这是一个简单的示例，你可能需要一个更复杂的实现
      return this.numberToWords(this.total) + ' Yuan Only'
    }
  },
  methods: {
    show() {
      this.visible = true
      this.fetchInvoiceData()
    },
    handleCancel() {
      this.visible = false
    },
    async fetchInvoiceData() {
      try {
        const response = await getInvoiceData(this.billId)
        this.invoiceData = response.data
      } catch (error) {
        console.error('获取发票数据失败:', error)
      }
    },
    numberToWords(number) {
      // 这是一个简单的实现，你可能需要一个更复杂的函数来处理所有情况
      const ones = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
      const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety']
      const teens = ['Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']

      if (number < 10) return ones[number]
      if (number < 20) return teens[number - 10]
      if (number < 100) return tens[Math.floor(number / 10)] + ' ' + ones[number % 10]
      if (number < 1000) return ones[Math.floor(number / 100)] + ' Hundred ' + this.numberToWords(number % 100)
      return 'Number too large'
    }
  }
}
</script>

<style scoped>
.invoice-print {
  font-family: SimSun, serif;
  width: 24cm;
  min-height: 27.5cm; /* 改为最小高度 */
  padding: 0;
  margin: 0 auto;
  box-sizing: border-box;
  background-color: white;
  position: relative;
  display: flex;
  flex-direction: column;
}

.invoice-content {
  border: 1px solid #000;
  padding: 3px;
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}

.invoice-header {
  margin-top: 0; /* 使公司名称紧贴顶部 */
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  border-bottom: 1px solid #000;
  padding-bottom: 10px;
}

.company-info {
  text-align: left;
}

.company-info h1 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.company-info p {
  margin: 5px 0;
  font-size: 14px;
}

.invoice-title {
  text-align: right;
}

.invoice-title h2 {
  margin: 0;
  font-size: 28px;
}

.invoice-title p {
  margin: 5px 0 0 0;
  font-size: 18px;
}

.invoice-details {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.customer-info, .invoice-info {
  width: 48%;
}

.invoice-table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

.invoice-table th, .invoice-table td {
  border: 1px solid #000;
  padding: 8px;
  text-align: left;
}

.invoice-table th {
  background-color: #f2f2f2;
}

.amount-in-words {
  margin-bottom: 10px;
}

.signature-section {
  margin-top: auto;
  display: flex;
  justify-content: space-between;
  padding-bottom: 20px;
}

.signature-item {
  text-align: center;
  width: 22%;
}

.signature-line {
  width: 80%;
  margin: 0 auto 5px;
  border-top: 1px solid #000;
}

.print-info {
  text-align: right;
  font-size: 0.9em;
}

.print-button-container {
  text-align: center;
  margin-top: 20px;
}

.print-button {
  padding: 10px 20px;
  font-size: 16px;
  background-color: #4CAF50;
  color: white;
  border: none;
  cursor: pointer;
  border-radius: 5px;
}

.print-button:hover {
  background-color: #45a049;
}

@page {
  size: 24cm 27.5cm;
  margin: 2;
}

@media print {
  html, body {
    margin: 0;
    padding: 0;
    height: 100%;
  }

  .invoice-print {
    height: 27.5cm; /* 打印时恢复固定高度 */
    overflow: visible;
    page-break-after: always;
    /* 确保打印时也没有边框 */
    border: none;
    position: relative; /* 确保打印时也有相对定位 */
  }

  .invoice-content {
    width: 100%;
    height: 100%;
    border: 1px solid #000; /* 打印时保留内容边框 */
    padding: 3px; /* 与非打印样式保持一致 */
  }

  .invoice-header {
    padding-top: 0;
  }

  .invoice-footer {
    margin-top: auto;
    padding: 0 0 0 0; /* 与非打印样式保持一致 */
  }

  .print-button-container {
    display: none;
  }

  /* 隐藏所有不必要的元素 */
  body > *:not(.invoice-print) {
    display: none !important;
  }

  .table-container {
    max-height: none; /* 打印时取消最大高度限制 */
    overflow-y: visible;
    overflow-x: auto; /* 允许表格横向滚动 */
  }

  .invoice-body {
    overflow: visible;
  }
}
</style>
